package com.gjy.scheduling.monitor.processor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ApplicationContextEvent;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-08-30 21:23:22
 */
public class SchedulerDsHandler extends AbstractDsHandler<SchedulerTaskInfo> implements ApplicationListener<ApplicationContextEvent> {

    private static final Logger log = LoggerFactory.getLogger(SchedulerDsHandler.class);

    private List<SchedulerTaskInfo> taskInfoList = new ArrayList<>();

    public void setTaskInfoList(List<SchedulerTaskInfo> taskInfoList) {
        this.taskInfoList = taskInfoList;
    }

    @Override
    protected ExecutorService getWorkerExecutor() {
        return ThreadLocalUtils.getExecutorService("kpi", 200);
    }

    @Override
    protected List<SchedulerTaskInfo> listTaskInfo() {
        return this.taskInfoList;
    }

    @Override
    protected void doProcess(SchedulerTaskInfo taskInfo) {
        final String reference = taskInfo.getReference();
        final String[] split = reference.split("#");
        if (split.length != 2) {
            return;
        }
        try {
            final Class<?> clazz = Class.forName(split[0]);
            final Method method = clazz.getMethod(split[1], SchedulerTaskInfo.class);
            method.invoke(clazz.newInstance(), taskInfo);
        } catch (Exception e) {
            log.error("");
        }
    }

    /**
     * 事件的ApplicationContext是root容器时才会执行。函数会获取主机ip，并每隔10秒扫描任务线程池中的任务，将任务信息存入任务信息列表中。
     */
    @Override
    public void onApplicationEvent(ApplicationContextEvent event) {
        //代表当前容器是root容器，否则监听器会被其他容器多次执行
        if (event.getApplicationContext().getParent() == null) {
            String ip = event.getApplicationContext().getEnvironment().getProperty("host");
            log.info("当前主机ip：{}", ip);
            //扫描任务线程池
            Executors.newScheduledThreadPool(1).scheduleAtFixedRate(() -> {
                // 这一块就是从数据库读取配置信息
                /*List<CfgKpiInfo> currCfgs = getCurrentCfgKpiInfos(ip);
                List<SchedulerTaskInfo> tasks = currCfgs.stream().map(cfg -> {
                    String monitorId = cfg.getMonitorId();
                    String cron = cfg.getCron();
                    String processId = cfg.getProcessId();
                    boolean isValid = cfg.getIsValid() == 1;
                    return SchedulerTaskInfo.builder().id(monitorId).cron(cron).isValid(isValid)
                            .sql1(cfg.getExecuteCommand()).sql2("").contactId(cfg.getContactId())
                            .expectValue(cfg.getExpectValue()).alarmContent(cfg.getAlarmContent()).emailTitle(cfg.getEmailTitle())
                            .type(cfg.getExecuteType()).reference(KpiConstant.METHOD_NAME).processId(processId)
                            .cfgKpiInfo(cfg).build();
                }).collect(Collectors.toList());
                setTaskInfoList(tasks);*/
                //每隔10s进行一次任务扫描
                LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(10));
            }, 5, 10, TimeUnit.SECONDS);
        }
    }
}
